<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@page import="java.io.File"%>
<%@page import="com.augurit.common.system.web.auth.form.LoginUserForm"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<% 
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
String dir=request.getSession().getServletContext().getRealPath("")+File.separator+"TEMP";


%>
<%LoginUserForm form=(LoginUserForm)request.getSession().getAttribute("SES_LOGIN_USER"); %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>盖章</title>

<%@ include file="/wf/public/meta_wf.jsp"%>
<script type='text/javascript' src="${ctx}/dwr/engine.js"></script>
<script type='text/javascript' src="${ctx}/dwr/util.js"></script>
<script type='text/javascript' src="${ctx}/dwr/interface/FileUploadCntl.js"></script>
<script  type="text/javascript" src="${ctx}/resources/js/jquery/jquery.js"></script>
<script src="${ctx}/gzcgwsp/resources/js/prototype.js" type="text/javascript"></script>
<script src="${ctx}/gzcgwsp/resources/js/YwUtil.js" type="text/javascript"></script>
<script src="${ctx}/gzcgwsp/resources/js/YwGrid.js" type="text/javascript"></script>
<script src="${ctx}/resources/js/aos/tool.js" type="text/javascript"></script>
<script src="${ctx}/resources/components/My97DatePicker/WdatePicker.js" type="text/javascript"></script>
<script src="${ctx}/common/apabiPrint/js/gaizhang.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/gzcgwsp/resources/css/common-ui.css" />

<script>
var filepath;
var viewStore;
var win;
var contextpath="<%=basePath%>";
var fileSavePath=getPathBySystem();
var basepath="${ctx}";
// 选中所有记录
function checkAll(chxEvent) {
  var chxs = document.getElementsByName("checkedIds");
  if (chxs && !chxs.length) { chxs.checked = chxEvent.checked; return; }
  if (chxs) for (var i = 0; i < chxs.length; i++) {
    chxs[i].checked = chxEvent.checked;
  }
}


//根据操作系统用不同的路径
function getPathBySystem(){
     var path="";
     var ua = navigator.userAgent.toLowerCase();
     if(ua.indexOf("linux")>=0){
        path="/usr/local/temp";
     }else{
        path="C:\\TEMP\\";
     }
    return path;
}

//文件下载
 function download(_v)
 { 
 document.getElementById("downloadURL").src=_v;
 }
//格式转换
function transMaker(DocName, CebName, LogName, IniName){
	var DTracker;
	DTracker = new ActiveXObject("MakerCom.MakerExt.1");
	var nRet;
	var Error;
	//alert("正转换文件，请稍候......");		
	nRet = DTracker.BeginMaker("");
	if (nRet != 0){
		alert(DTracker.GetErrorMessage(nRet));		
		delete DTracker;
		return false;
	}		
    //alert("开始文档格式转换......请稍后!");		
	nRet = DTracker.SingleFileConvert(DocName, CebName, "标准模板", LogName, IniName);	
	if (nRet != 0){
		alert("MakerOcx transfer error!");
		nRet = DTracker.EndMaker();		
		delete DTracker;
		return false;
	}
	nRet = DTracker.EndMaker();
	if (nRet != 0){
		alert("MakerOcx End error!");		
		delete DTracker;
		return false;
	}	
	//alert("格式转换完成！");	
	delete DTracker;
	return true;
}

//删除文件
function deleteFile(){     
   var wshShell =new ActiveXObject("WScript.Shell");          
    //fso用来处理文件和文件夹   
    var fso = new ActiveXObject("Scripting.FileSystemObject");   
       
    //path删除文件的路径   
    var path = "c:\\temp";   
    //如果指定的文件夹存在则返回 True ；否则返回 False   
    if(fso.FolderExists(path)){   
      try{   
           fso.DeleteFile(path+"\\*.*");  
       }catch(e){   
             alert(".ceb" + e.message);   
       }   
              
   }else{   
           alert("不存在这个目录："+path);   
        }   
   }   
//盖章
function gaizhang(){
  //获取盖章的id
   var chxs = document.getElementsByName("checkedIds");
   var idval="";
   var filepath="";
   var gzName="";
   var fileTitle="";
   for (var i = 0; i < chxs.length; i++) {
    if (chxs[i].checked) { 
    	gzName=chxs[i].getAttribute("gzName");
    	filepath=chxs[i].getAttribute("path");
    	fileTitle=chxs[i].getAttribute("fileName");
    	idval += chxs[i].value+",";
    }
    }
    if(idval==""){
	    alert("请选择单条记录");
	    return ;
    }
    if(idval.length>0){
    	idval=idval.substring(0,idval.length-1);
    	var idlen=idval.split(",");
    	if(idlen.length>1){
    		alert("请选择单条记录");
    		 return ;
    	}
  }
    	filepath=contextpath+filepath;
  		var chinesename =gzName;
  		var filename = filepath.substring(filepath.lastIndexOf("/")+1);
 		TransUpload(filename,chinesename,fileTitle);

}


function TransUpload(result,chinesename,fileTitle){
	MakeWord(result,chinesename);// 打开word ，把它保存在D盘，相当于下载
	var DocName, CebName, LogName, IniName;
	var DocNameLen;
	var DocNameWONLen;
	var cebtail;

//	DocName = NewDocForm.OriginalFile.value;
 	DocName =fileSavePath+chinesename;
	DocNameLen = DocName.length;
	DocNameWONLen = DocName.lastIndexOf(".") - 1;
	if (DocNameWONLen == -1){
		DocNameWONLen = DocNameLen;
	}else{
		cebtail = DocName.substring(DocNameWONLen+2, DocNameLen);
	}
	if (cebtail.toLowerCase() == "ceb"){
		CebName = DocName;
	}else{
		CebName = DocName.substring(0, DocNameWONLen+1) + ".ceb";
	}
	
	LogName = DocName.substring(0, DocNameWONLen+1) + ".log";
	IniName = DocName.substring(0, DocNameWONLen+1) + ".ini";
	if (DocName != CebName){
		if (!(transMaker(DocName, CebName, LogName, IniName))){// 格式转换
			alert("格式转换失败，请重试！");
			return false;
		}		
	}
	else{
		alert("当前格式为ceb格式！");
	}
	var f=fileSavePath+chinesename.substring(0,chinesename.lastIndexOf("."))+".ceb";
	//alert(f);
	Stamp_onclick(f);//盖章	
	 var ieflag=checkIeVersion();
	 if(ieflag){
 		//document.getElementById("t1").value=f;
		//callSet(fileTitle);//上传
		Ext.getBody().mask("附件上传中");
	 	fileuploaddoc(f,'${id}','${templateCode}',fileTitle);
	 }else{
	 	Ext.getBody().mask("附件上传中");
	 	fileuploaddoc(f,'${id}','${templateCode}',fileTitle);
	 }
	return true;
}

//判断ie的版本，如果是6.0或者7.0返回true;
function checkIeVersion(){
	var browser=navigator.appName 
	var b_version=navigator.appVersion 
	var version=b_version.split(";"); 
	var trim_Version=version[1].replace(/[ ]/g,""); 
	if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE6.0"){ 
		return true;
	} else if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE7.0"){ 
		return false;
	} else if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE8.0"){ 
		return false;
	} else if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE9.0") { 
		return false;
	} else if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE9.0") { 
		return false;
	}else if(browser=="Microsoft Internet Explorer" && trim_Version=="MSIE9.0") { 
		return false;
	}
	return true;
}

 function MakeWord(filename,chinesename){
		//var openDocObj = new ActiveXObject("SharePoint.OpenDocuments.2"); // 为了兼容Office XP，可以创建“SharePoint.OpenDocuments.1” 
		//openDocObj.ViewDocument("http://192.168.15.253:8888\\gzcgwsp\\printdoc\\rqjyxkz_gdqy\\1309923429718.doc");  
		//openDocObj.EditDocument("http://192.168.15.253:8888\\gzcgwsp\\printdoc\\rqjyxkz_gdqy\\1309923429718.doc");
	try{ 
	
        var WordApp=new ActiveXObject("Word.Application");
        WordApp.Application.Visible=false; 
        WordApp.NormalTemplate.Saved = true;
        var  templatecode="${templateCode}";
        var url=contextpath+"/printdoc/"+templatecode+"/"+filename;
        try{
	        var Doc=WordApp.Documents.Add(url,false);
	        Doc.saveAs(fileSavePath+chinesename);
	        Doc.Close();
	        WordApp.Quit();
        }catch(e){
        	 alert("文件不存在"); 
        }
	}catch(e){ 
	    alert("无法调用Office对象，请确保您的机器已安装了Office并已将IE安全级别降低！"); 
	}

 }
</script>

<script language="vbs">
Function Stamp_onclick(strCEBFileName)    	
	Dim strErrMessage, lRet, objStampClientTool,g_AffixRegisterURL,g_SendPrintURL,UnitName
	g_AffixRegisterURL="http://172.16.253.169/StampServer/interfaces/background/AffixRegister.aspx"
	g_SendPrintURL="http://172.16.253.169/StampServer/extend/interfaces/SendPrint.aspx"
	UnitName=""

	lRet = ""
	strErrMessage = ""
	strCEBFileName = trim(strCEBFileName)

	if  0 = len(trim(strCEBFileName)) then
		Call Alert("请选择CEB文件！", vbExclamation, "请选择CEB文件！")
		Exit Function
	else
		if UCase(Right(Trim(strCEBFileName), 3)) <> "CEB" then
			Call Alert("只能选择CEB格式的文件！", vbExclamation, "只能选择CEB格式的文件！")
			CEBFileName.value = ""
			Exit Function
		end if                  	 	  
	end if

	set objStampClientTool  = CreateObject("StampClientTool.StampTool")

	' 本地可视化盖章	
	lRet = objStampClientTool.LocalSealStamp(strCEBFileName, UnitName, g_AffixRegisterURL, g_SendPrintURL)
	
	if lRet <> 0 then
		strErrMessage = objStampClientTool.GetErrorMessage()
        alert "盖章失败原因:" & strErrMessage
	end if

	Set objStampClientTool = Nothing	
End Function


</script>
<script LANGUAGE="JavaScript">
//简化写法
function $(id){
    return document.getElementById(id);
}
//崋值方法(就是将文本框的值赋值file对象)
function set1(){
    //将text1中的值复制到剪贴板中
    window.clipboardData.setData('text',$('t1').value); 
    //创建Shell(需要添加到信任站点或解除未签名的ActiveX控件的禁用
    var   WshShell=new   ActiveXObject("WScript.Shell"); 
    //拿到焦点
    $('f1').focus();
    //Ctrl + A 操作
    WshShell.sendKeys("^a");
    //Ctrl + V 操作(sendKeys对于中文赋值操作显得无力,所以只能模拟键盘操作)
    WshShell.sendKeys("^v");
    
}

//给当前网页中四个file对象赋值的方法
function set(chinesename){
    //此处不要用循环,有几个就需要写几个setXX方法
    setTimeout("set1()",3000);
    setTimeout("upload('"+chinesename+"')",2000);
}
//检查是否赋值成功
function check(){
    //检查每个file对象是否为空 
    if($('f1').value.length > 0){
        //检查原对象的值的赋值对象的值是否相同
        if($('f1').value == $('t1').value){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
//赋值和file对象的检查
function setValues(chinesename){
    if(!check()){
        set(chinesename);
    }
}
//直接调用的赋值方法
function callSet(chinesename){
    //一定要用setInterval,而不能用循环(循环太快,会造成所有的值赋在一个file对象上)
    //setInterval('setValues()',1000);
    setValues(chinesename);    
}

function upload(chinesename){
var attache = dwr.util.getValue('f1');
var uploadName=dwr.util.getValue('f1').value;
if (uploadName == '') { 
     uploadName=$('t1').value;
    //Ext.Msg.alert("提示!","上传失败!");return;
}
var ajid='${id}';
var username='<%=form.getUser().getUserName() %>';
var dotIndex =uploadName.lastIndexOf(".");
if (dotIndex < 0) dotIndex = uploadName.length;
var attacheName = chinesename;
var attacheType = uploadName.substring(dotIndex + 1);
var obj;	
 obj ={
  ajid:ajid,
  username:username,
  filename:attacheName,
  filetype:attacheType
  };	
	
var params=Ext.encode(obj);
FileUploadCntl.uploadDzgz(params, attache, function (result){
       Ext.Msg.alert("提示!","上传成功!");
       window.location.reload(); 
       //viewStore.load();
});
}


//弹出上传文件的窗口
function fileWin(chinesename,uploadName){
	var ajid='${id}';
	var templateCode='${templateCode}';
	var username='<%=form.getUser().getUserName() %>';
	var dotIndex =uploadName.lastIndexOf(".");
	if (dotIndex < 0) dotIndex = uploadName.length;
	var attacheName = chinesename;
	var attacheType = uploadName.substring(dotIndex + 1);
	new Ext.Window({
	    id        : 'fileWin',
	    title     : '选择证书',
	    width     : 450,
	    height    : 150,
	    modal     : true,
	    plain     : true,
	    resizeable: false,
        html: '<br>' +
       '<form action="${ctx}/yw-com-print!uploadAttach.action"  enctype="multipart/form-data" id="fileform" name="fileform" method="post" target="upload-target">' +
       '<input type="hidden" name="templateCode" value="'+templateCode +'"/>'+
        '<input type="hidden" name="ajid" value="' +ajid+'"/>'+
         '<input type="hidden" name="attacheName" value="' +attacheName+'"/>'+
         '<input type="hidden" name="filetype" value="' +attacheType+'"/>'+
         '<input type="hidden" name="username" value="' +username+'"/>'+
        '<table width="100%" border="0">' +
        '    <tr>' +
        '        <td align="right" height="25">选择证件：</td>' +
        '        <td colspan="3"><input type="file" id="attacheBrow" name="attach"  size="35" class="tpl_list_ui"/></td>' +
        '    </tr>' +
        '    <tr>' +
        '        <td colspan="4" align="center">&nbsp;</td>' +
        '    </tr>' +
        '    <tr>' +
        '        <td colspan="4" align="center">' +
        '            <input type="button" value="上  传" onclick="uploadFile();" class="tpl_list_ui"/>' +
        '            &nbsp;&nbsp;&nbsp;&nbsp;' +
        '            <input type="button" value="取  消" onclick="Ext.getCmp(\'fileWin\').hide();" class="tpl_list_ui"/>' +
        '        </td>' +
        '    </tr>' +
        '</table>' +
        '<iframe name="upload-target" style="display:none;"></iframe>' +
        '</form>' +
    ''
  }).show();
}

function uploadFile(){
  document.getElementById("fileform").submit();
}

function resultValue(result){
 var faile = Ext.decode(result);
	if(faile.msg==false){
		Ext.Msg.alert("提示!","上传失败!");
	}else{
	    Ext.Msg.alert("提示!","上传成功!");
	    //删除c:temp下的文件
		deleteFile();
	    Ext.getCmp('fileWin').close();
	    window.location.reload(); 
	}
}

function  viewGzFile(path,filename){
	filename=filename.substring(0,filename.lastIndexOf("."));
	filename+=".ceb";
	filename=encodeURI(encodeURI(filename))
	var url="yw-com-print!checkFile.action?url="+path;
	//检查文件是否存在
	 Ext.Ajax.request({
	     url:url,
	     method:'POST',
	     timeout:900000,
	     method:'POST',
	     success:function(response){
	         var msg=response.responseText;
	         if(msg=="true"){
				window.location.href = "${ctx}/common/downloadfile.jsp?filepath="+path+"&filename="+filename;  
			}else{
				alert('文件不存在！');
			}
		},
	    failure: function() {
	        Ext.Msg.alert('错误', '请求失败,请稍后重试'); 
	        myMask.hide();
	     } 
   });
}
</script>
</head>

<body>
<form action="yw-com-print!dzgz.action" method="post" >
<div id="fileid" style="display:none">
		<input type="text" style="height:10" id="t1" />
		<input style="height:10" type="file" name="f1" id="f1"/> <br />
	</div>
  <table width="100%" border="0" cellspacing="2" cellpadding="2">
    <tr>
      <td>
        <table width="100%" border="0" cellspacing="2" cellpadding="2" class="tpl_list_blueui">
          <tr>
            <td height="10" width='50%' align="center" bordercolor="#B3D9D9">
              &nbsp;&nbsp;
              <font size="4">文书列表</font>
            </td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td>
        <table width="100%" border="1" cellspacing="0" cellpadding="2" class="tpl_list_blueui">
          
        </table>
      </td>
    </tr>
    <tr>
      <td>
       <table width="100%" border="1" cellspacing="2" cellpadding="2" class="tpl_list_blueui">
          <tr>
            <td height="20" bordercolor="#B3D9D9" bgcolor="#D9E8FB">
              <table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td width="50%">&nbsp;&nbsp;<b>文书信息列表</b></td>
                  <td width="50%" align="right">
                    <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#D9E8FB">
                      <tr>
                        <td height="20">&nbsp;</td>
                        <td width="80">
                          <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#D9E8FB" onmouseover="this.className='tpl_btn_omover'" onmousedown="this.className='tpl_btn_omdown'" onmouseout="this.className='tpl_btn_omout'" onclick="gaizhang();">
                            <tr>
                              <td height="20" align="center"><img src="${ctx}/resources/images/icons1616/Add.gif" />&nbsp;盖&nbsp;&nbsp;章</td>
                            </tr>
                          </table>
                        </td>
                        <td width="80">
                          <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolor="#D9E8FB" onmouseover="this.className='tpl_btn_omover'" onmousedown="this.className='tpl_btn_omdown'" onmouseout="this.className='tpl_btn_omout'" onclick="window.close();">
                            <tr>
                              <td height="20" align="center"><img src="${ctx}/resources/images/icons1616/Edit.gif" />&nbsp;关&nbsp;&nbsp;闭</td>
                            </tr>
                          </table>
                        </td>
                   
                      </tr>
                    </table>
                  </td>
                </tr>
            </table></td>
          </tr>
      </table></td>
    </tr>
     <tr>
      <td>
      <table width="100%" border="1" cellspacing="2" cellpadding="2" class="tpl_list_blueui">
        <tr>
          <td width="8%" height="20" align="center" bordercolor="#B3D9D9" bgcolor="#E7EEF8">
            <input type="checkbox" id="checkall" title="全选" onclick="checkAll(this)" />
          </td>
          <td width="35%" align="center" bordercolor="#B3D9D9" bgcolor="#E7EEF8">文书名称</td>
          <td width="10%" align="center" bordercolor="#B3D9D9" bgcolor="#E7EEF8">是否盖章</td>
          <td width="15%" align="center" bordercolor="#B3D9D9" bgcolor="#E7EEF8">盖章人</td>
          <td width="15%" align="center" bordercolor="#B3D9D9" bgcolor="#E7EEF8">盖章日期</td>
          <td width="15%" align="center" bordercolor="#B3D9D9" bgcolor="#E7EEF8">查看盖章文件</td>
          <td width="" align="center" style="display:none">filepath</td>
          <td width="" align="center" style="display:none">gzname</td>
        </tr>
        <s:iterator value="#request.resultList" id="status">  
          <tr >
           <td bordercolor="#B3D9D9" height="20" align="center">
              <input type="checkbox" name="checkedIds" path="<s:property value="path"/>" fileName="<s:property value="fileName"/>" gzName="<s:property value="gzName"/>" value="<s:property value="id"/>" />
            </td>
            <td height="20" align="center" bordercolor="#B3D9D9">
              <s:property value="fileName"/>
            </td>
            <td align="center" bordercolor="#B3D9D9">
             <s:if test="gzpath!=null">
             	已盖章
             </s:if>
              <s:else>未盖章</s:else>
             </td>
            <td align="center" bordercolor="#B3D9D9">
              <s:property value="gzname"/>
			</td>
			 <td align="center" bordercolor="#B3D9D9">
			 <s:date name="gzdate" format="yyyy-MM-dd"/>
			</td>
			<td width="" align="center" style="display:none"> <s:property value="path"/></td>
			<td width="" align="center" style="display:none"> <s:property value="gzName"/></td>
			<td align="center" bordercolor="#B3D9D9">
			  <s:if test="gzpath!=null">
				<a href="#" onclick="viewGzFile('<s:property value="gzpath"/>','<s:property value="fileName"/>');">查看</a>
             </s:if>
             </td>
          </tr>
        </s:iterator>
      </table>
     </td>
    </tr>
  </table>

</form>
</body>
</html>
